var rMenu;//树的右键菜单
var zTree;
var gNode;
var setting = {
	async : {
		enable : true,
		url :"/do/type/getAll",
	},data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
        },
    },
	callback : {
		onRightClick : OnRightClick,
		onAsyncSuccess: zTreeOnAsyncSuccess  
	}
};

function zTreeOnAsyncSuccess(event, treeId, msg) { 
	//异步加载完后展开到第二级节点
	var nodes = zTree.getNodes();
    for (var i = 0; i < nodes.length; i++) { //设置节点展开
    	zTree.expandNode(nodes[i], true, false, true);
    }
}
//初始化
$(document).ready(function() {
	$.fn.zTree.init($("#tree"), setting);
	zTree = $.fn.zTree.getZTreeObj("tree");
	rMenu = $("#rMenu");
	hideRMenu();
	
	$("#add").bind("click",btnAddChildNodes);
	$("#delete").bind("click",btnDeleChildNodes);
	$("#modify").bind("click",btnModifyNode);
	
	$('#myModal').on('hidden.bs.modal', modalHiddenEvent);//模态框隐藏触发
	$("#m_btn").bind("click",saveOrUpdateNode);
});

//ztree 右键方法
function OnRightClick(event, treeId, treeNode) {
	if (!treeNode && event.target.tagName.toLowerCase() != "button"
			&& $(event.target).parents("a").length == 0) {
		zTree.cancelSelectedNode();
		gNode=null;
		showRMenu("root", event.clientX, event.clientY);
	} else if (treeNode && !treeNode.noR) {
		zTree.selectNode(treeNode);
		gNode=treeNode;
		showRMenu("node", event.clientX, event.clientY);
	}
}

//展示右键菜单
function showRMenu(type, x, y) {
	$("#rMenu ul").show();
	if (type == "root") {
		$("#modify").hide();
		$("#delete").hide();
	} else {
		$("#modify").show();
		$("#delete").show();
	}
	rMenu.css({
		"top" : y + "px",
		"left" : x + "px",
		"visibility" : "visible"
	});

	$("body").bind("mousedown", onBodyMouseDown);
}

//隐藏右键菜单
function hideRMenu() {
	if (rMenu)
		rMenu.css({
			"visibility" : "hidden"
		});
	$("body").unbind("mousedown", onBodyMouseDown);
}
function onBodyMouseDown(event) {
	if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
		rMenu.css({
			"visibility" : "hidden"
		});
	}
}

var rMenuBtnType=0;
/**
 * 点击添加下级
 */
function btnAddChildNodes(){
	hideRMenu();
	rMenuBtnType=1;
	$('#myModal').modal('show');
	if(gNode && gNode!=null){
		//$("#typeName").val(gNode.name);
		$('#myModalLabel').html(gNode.name+"-添加下级");
	}else{
		$('#myModalLabel').html("添加下级");
	}
}

function btnModifyNode(){
	hideRMenu();
	rMenuBtnType=2;
	$('#myModal').modal('show');
	if(gNode && gNode!=null){
		$("#typeName").val(gNode.name);
		$('#myModalLabel').html(gNode.name+"-编辑");
	}
}
/**
 * 点击删除
 */
function btnDeleChildNodes(){

    hideRMenu();
    if(gNode.children && gNode.children.length>0){
        Ewin.alert("该类别有下级，请先删除下级");
        return ;

	}
    Ewin.confirm({message: "确认要删除该类别吗？"}).on(function (e) {
        if (!e) {
            return;
        }

        $.ajax({
            type: 'delete',
            url: '/do/type/'+gNode.id,

            dataType:"json",
            success: function (data) {
                if(data.code==1){
                    //移除页面上的节点
                    zTree.removeNode(gNode);
                }else{
                    alert(data.msg)
                }
            },
            complete: function () {
            }
        });
    });

}

/**
 * 模态框隐藏后 清空form表单数据
 */
function modalHiddenEvent(){
	gNode=null;
	$("#typeName").val("");
	rMenuBtnType==0;
}

function saveOrUpdateNode(){
	
	var pid="",id="",name="";
	if(rMenuBtnType==1){//添加下级
		if( gNode!=null){
			pid=gNode.id;
		}
		
	}else if(rMenuBtnType==2){
		pid=gNode.pid;
		id=gNode.id;
	}else{
		return ;
	}
	name=$("#typeName").val();
	if(name == "" || name==null){
		return ;
	}
	$("#m_btn").attr('disabled',"true");
	$.ajax({
        type: 'post',
        url: '/do/type/edit',
        data: {
        	id:id,
        	pid:pid,
        	name:name
        },
        dataType:"json",
        success: function (data) {
        	$('#m_btn').removeAttr("disabled");
        	if(data.code==1){
        		$('#myModal').modal('toggle');
        		if(rMenuBtnType==1){
        			if(data.data){
        				zTree.addNodes(gNode, {id:data.data.id, pId:data.data.pid, isParent:false, name:data.data.name});
        			}
        		}else{
        			zTree.reAsyncChildNodes(null, "refresh", false);
        		}
        	}else{
        		$('#errorMsg').html(data.msg);
        		//2秒后隐藏
        		$('#errorMsg').delay(2000).queue(function(){$(this).html("");}) 
        		
        	}
        },
        
        complete: function () {
        }
    });
}

